package com.gmstu.defaults.action;

import com.gmstu.defaults.service.IActionService;
import com.gmstu.mvcservlet.annotation.GpAutowired;
import com.gmstu.mvcservlet.annotation.GpController;
import com.gmstu.mvcservlet.annotation.GpRequestMapping;
import com.gmstu.mvcservlet.annotation.GpRequestParam;
import com.gmstu.springframework.mvc.servlet.GpModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author John.zhang
 * @version Id: ActionController, v 1.0 2020/7/29 14:38 ZhiYong Exp $
 */
@GpController
@GpRequestMapping("/action")
public class ActionController {

    @GpAutowired
    private IActionService actionService;

    @GpRequestMapping("query")
    public GpModelAndView query(HttpServletRequest req, HttpServletResponse resp, @GpRequestParam("name") String name) {
        String result;
        try {
            result = actionService.get(name);
            return getResult(resp, result);
        } catch (Exception e) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("detail", e.getMessage());
            model.put("stackTrace", Arrays.toString(e.getStackTrace()).replace("\\[|\\]", ""));
            return new GpModelAndView("500", model);
        }
    }


    private GpModelAndView getResult(HttpServletResponse resp, String str) {
        try {
            resp.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
